<template>
	<u-modal :show="show" :negativeTop="200" :title="title" confirmText="确定" showCancelButton confirmColor="#FD8906"
		cancelColor="#000" @confirm="save" @cancel="show = false" @close="show = false" zoom width="700rpx">
		<view class="f-1 w100 f12 ggwrap">
			<view class="f-bt f-y-c bf p2">
				<view class="f-g-1">
					<u-input placeholder="请输入加料名称" v-model="queryForm.keyword" @change="fetchData" prefixIcon="search"
						shape="circle"
						prefixIconStyle="font-size: 22px;color: #666;margin-right:10rpx;padding-left:10px"
						placeholderStyle="color:#666" customStyle="background:#f8f8f8;padding:15rpx 5rpx;" border="none"
						clearable>
					</u-input>
				</view>
			</view>
			<view class="uni-container mt10 f14">
				<uni-table ref="table" border stripe emptyText="暂无数据">
					<uni-tr>
						<uni-th align="center">加料名称</uni-th>
						<uni-th align="center" width="350">加料商品</uni-th>
					</uni-tr>
					<uni-tr v-for="(row, i) in tableData" :key="i">
						<uni-td align="center">
							<view class="f-x-ad">
								<!-- <radio :color="subColor" :label="row.id" :checked="xzId == row.id"
									@click="handleCheckAllChange(row)" />
								<view class="radio">{{row.name}}</view> -->
								<u-checkbox :activeColor="subColor" :label="row.name"
									:checked="checkData.find(v => v.id == row.id)" :name="row.id"
									@change="handleCheckAllChange(row,$event)"></u-checkbox>
							</view>
						</uni-td>
						<uni-td align="center">
							<view v-if="row.materialList && row.materialList.length > 0" class="f-w">
								<u-checkbox-group v-model="row.checkList" placement="row"
									@change="handleCheckOneChange(row, $event)">
									<u-checkbox :activeColor="subColor" :label="`${item.name} ￥${item.price}`"
										v-for="(item, index) in row.materialList" :key="index"
										:customStyle="{marginRight: '8px'}" :name="item.id"></u-checkbox>
								</u-checkbox-group>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box"><uni-pagination show-icon :page-size="queryForm.pageSize"
						:current="queryForm.pageNo" :total="total" @change="change" /></view>
			</view>
			<!-- <view class="buts mt20">
				<view class="p-0-20 mb10">
					<view class="cf bs30 tac p10 f14 wei" :style="{background:subColor,color:'#000'}" @click="handAdd">
						新增规格
					</view>
				</view>
			</view> -->
		</view>
	</u-modal>
</template>

<script>
	import {
		mapState,
	} from 'vuex'
	import site from '@/custom/siteroot.js';
	import config from '@/custom/config.js';
	export default {
		components: {

		},
		props: {
			mode: {
				type: String,
				default: () => 'single'
			},
			v: {
				type: Object,
				default: () => {}
			}
		},
		data() {
			return {
				subColor: uni.getStorageSync('subject_color'),
				queryForm: {
					keyword: "",
					pageNo: 1,
					pageSize: 10,
				},
				show: false,
				list: [],
				total: 0,
				checkData: [],
				tableData: [],
				loading: true,
				currentFactor: 0,
				xzId: 0,
				title:'',
			}
		},
		computed: {
			...mapState({
				storeId: state => state.storeId,
			}),
		},
		methods: {
			open(list) {
				this.checkData = JSON.parse(JSON.stringify(list));
				this.fetchData();
				this.show = true
			},
			async fetchData(type) {
				this.status = 'loading'
				let {
					data: {
						list,
						pageNo,
						pageSize,
						total
					},
				} = await this.beg.request({
					url: `${this.api.materialCatList}`,
					data: this.queryForm,
				})
				this.tableData = list
				 if (this.checkData.length > 0) {
				        for (let i = 0; i < list.length; i++) {
				          for (let j = 0; j < this.checkData.length; j++) {
				            if (list[i].id == this.checkData[j].id) {
				              list[i].checkList = this.checkData[j].checkList;
				              let totalCount = list[i].materialList.length;
				              let someStatusCount = list[i].checkList.length;
				              list[i].checkAll = totalCount === someStatusCount ? true : false;
				              list[i].isIndeterminate =
				                someStatusCount > 0 && someStatusCount < totalCount;
				            }
				            if (!list[i].checkAll) {
				              list[i].checkAll = false;
				            }
				            if (list[i].checkList) {
				              if (list[i].checkList.length == list[i].materialList.length) {
				              }
				            }
				          }
				        }
				      }
			},
			change(e) {
				this.queryForm.pageNo = e.current;
				this.fetchData()
			},
			close() {
				this.form = {
					sort: 1,
					name: '',
					desc: '',
					value: [{
						name: "",
						img: ""
					}]
				}
				this.fileList1 = []
				this.show = false
			},
			handleCheckAllChange(v, val) {
				v.isIndeterminate = false
				this.tableData.forEach((item) => {
					let len = item.materialList,
						carr = [];
					if (v.id == item.id) {
						for (let i = 0; i < len.length; i++) {
							carr.push(len[i].id);
							item.checkList = carr;
						}
						if (!val) {
							item.checkList = [];
						}
					}
				});
				if (val) {
					if (this.checkData.find(f => f.id == v.id)) {
						let fi = this.checkData.findIndex((x) => x.id == v.id);
						this.checkData[fi] = v;
					} else {
						this.checkData.push(v);
					}
				} else {
					let i = this.checkData.findIndex((x) => x.id == v.id);
					this.checkData.splice(i, 1);
				}
			},
			handleCheckOneChange(obj, e) {
				let list = obj.materialList;
				      let flag = true;
				      var cd = JSON.parse(JSON.stringify(this.checkData))
				      if (e && e.length > 0) {
				        if (cd && cd.length > 0) {
							obj.checkList = e
				          cd.forEach((data) => {
				            if (data.id == obj.id) {
				              flag = false;
				              data.checkList = e;
				              data.materialList = [];
				              for (let i = 0; i < list.length; i++) {
				                e.forEach((attr) => {
				                  if (list[i].id == attr) {
				                    data.materialList.push(list[i]);
				                  }
				                });
				              }
				            }
				          });
				          this.checkData = cd
				        }
				        if (flag) {
				          let addData = JSON.parse(JSON.stringify(obj));
				          addData.materialList = [];
				          for (let i = 0; i < list.length; i++) {
				            e.forEach((attr) => {
				              if (list[i].id == attr) {
				                addData.materialList.push(list[i]);
				              }
				            });
				          }
				          this.checkData.push(addData);
				        }
				      } else {
				        let i = this.checkData.findIndex((x) => x.id == obj.id);
				        this.checkData.splice(i, 1);
						// console.log(2345,this.checkData)
				      }
				      let totalCount = obj.materialList.length;
				      let someStatusCount = e.length;
				      obj.checkAll = totalCount === someStatusCount ? true : false;
				      obj.isIndeterminate = someStatusCount > 0 && someStatusCount < totalCount;
			},
			async save() {
				console.log('state', this.checkData);
				this.$emit("edit-spec", this.checkData);
				this.close()
			}
		},
	}
</script>

<style lang="scss" scoped>
	.ggwrap {
		max-height: 900rpx;
		overflow: hidden;
		overflow-y: scroll;
	}

	.left {
		width: 110rpx;
		text-align: right;
	}

	.ggz {
		background: #f7f8fa;

		.srggz {
			width: 120rpx;
		}
	}
</style>